import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { DoiTask, DoiItem, Notification } from '@/types';
import { v4 as uuidv4 } from 'uuid';

export const useTaskStore = defineStore('task', () => {
  // 状态 - 使用数组而不是对象
  const tasks = ref<DoiTask[]>([]);
  const selectedTaskId = ref<string | null>(null);
  const clientId = ref<string>(localStorage.getItem('clientId') || uuidv4());
  const connectionId = ref<string | null>(null);
  const notifications = ref<Notification[]>([]);
  const currentTaskType = ref<'DOI' | 'JiangSu'>('DOI'); // 添加当前任务类型
  
  // 初始化客户端ID
  if (!localStorage.getItem('clientId')) {
    localStorage.setItem('clientId', clientId.value);
  }
  
  // 计算属性 - 按当前任务类型过滤并按开始时间排序的任务列表
  const sortedTasks = computed(() => {
    // 确保 tasks.value 是数组且不为 null 或 undefined
    if (!tasks.value || !Array.isArray(tasks.value)) {
      return [];
    }
    
    // 按当前任务类型过滤
    const filteredTasks = tasks.value.filter(task => 
      !task.task_type || task.task_type === currentTaskType.value
    );
    
    return [...filteredTasks].sort((a, b) => {
      return new Date(b.start_time).getTime() - 
             new Date(a.start_time).getTime();
    });
  });
  
  // 方法
  function addTask(task: DoiTask) {
    // 如果任务没有指定类型，则使用当前类型
    if (!task.task_type) {
      task.task_type = currentTaskType.value;
    }
    tasks.value.push(task);
  }
  
  function updateTaskStatus(taskId: string, statusData: Partial<DoiTask>) {
    const taskIndex = tasks.value.findIndex(task => task.task_id === taskId);
    if (taskIndex === -1) {
      // 如果任务不存在，则创建新任务
      const newTask: DoiTask = {
        task_id: taskId,
        start_time: statusData.start_time || new Date().toISOString(),
        status: statusData.status || 'pending',
        total_dois: statusData.total_dois || 0,
        completed_dois: statusData.completed_dois || 0,
        success_dois: statusData.success_dois || 0,
        failed_dois: statusData.failed_dois || 0,
        progress: statusData.progress || 0,
        dois: statusData.dois || []
      };
      
      // 添加其他可选字段
      if (statusData.file_name) newTask.file_name = statusData.file_name;
      if (statusData.end_time) newTask.end_time = statusData.end_time;
      if (statusData.download_url) newTask.download_url = statusData.download_url;
      
      // 添加新任务
      tasks.value.push(newTask);
      // 移除保存到本地存储
      return;
    }
    
    // 检查是否是任务完成的状态变更
    const oldStatus = tasks.value[taskIndex].status;
    const newStatus = statusData.status || oldStatus;
    
    // 更新任务数据
    tasks.value[taskIndex] = { ...tasks.value[taskIndex], ...statusData };
    
    // 计算进度
    if (statusData.total_dois && (statusData.completed_dois !== undefined || statusData.failed_dois !== undefined)) {
      const completed = statusData.completed_dois || tasks.value[taskIndex].completed_dois;
      const total = statusData.total_dois;
      const progress = (completed / total) * 100;
      tasks.value[taskIndex].progress = progress;
    }
    
    // 移除保存到本地存储
    
    // 如果任务状态从处理中变为完成或失败，显示通知
    if (oldStatus === 'processing' && (newStatus === 'completed' || newStatus === 'failed')) {
      const notificationType = newStatus === 'completed' ? 'success' : 'error';
      const notificationTitle = newStatus === 'completed' ? '任务完成' : '任务失败';
      const notificationMessage = newStatus === 'completed' ? 
        `任务 ${taskId.substring(0, 8)}... 已成功完成` : 
        `任务 ${taskId.substring(0, 8)}... 处理失败`;
      
      addNotification(notificationType, notificationTitle, notificationMessage);
    }
  }
  
  function updateMetadataStatus(taskId: string, data: DoiItem) {
    // 查找任务
    const taskIndex = tasks.value.findIndex(task => task.task_id === taskId);
    if (taskIndex === -1) return;
    
    // 确保任务有dois数组
    if (!tasks.value[taskIndex].dois) {
      tasks.value[taskIndex].dois = [];
    }
    
    // 查找是否已存在该DOI
    const existingIndex = tasks.value[taskIndex].dois.findIndex(item => 
      item.doi === data.doi
    );
    
    // 更新或添加DOI元数据
    if (existingIndex >= 0) {
      // 更新现有DOI的元数据
      tasks.value[taskIndex].dois[existingIndex] = {
        ...tasks.value[taskIndex].dois[existingIndex],
        ...data
      };
    } else {
      // 添加新的DOI元数据
      tasks.value[taskIndex].dois.push(data);
    }
    
    // 移除保存到本地存储
  }
  
  function clearAllTasks(showNotification: boolean = true) {
    // 只清除当前类型的任务
    tasks.value = tasks.value.filter(task => 
      task.task_type && task.task_type !== currentTaskType.value
    );
    selectedTaskId.value = null;
    
    if (showNotification) {
      addNotification('info', '已清空任务', `所有${currentTaskType.value === 'DOI' ? 'Sci-Hub' : 'JiangSu'}任务记录已清除`);
    }
  }
  
  // function saveTasksToLocalStorage() {
  //   localStorage.setItem('doiTasks', JSON.stringify(tasks.value));
  // }
  
  // function loadTasksFromLocalStorage() {
  //   const savedTasks = localStorage.getItem('doiTasks');
  //   if (savedTasks) {
  //     try {
  //       const parsedTasks = JSON.parse(savedTasks);
  //       // 确保解析后的数据是数组
  //       tasks.value = Array.isArray(parsedTasks) ? parsedTasks : [];
  //     } catch (error) {
  //       console.error('加载本地任务失败:', error);
  //       localStorage.removeItem('doiTasks');
  //       tasks.value = [];
  //     }
  //   }
  // }
  
  function addNotification(type: 'success' | 'error' | 'info' | 'warning', title: string, message: string, timeout = 3000) {
    const id = uuidv4();
    notifications.value.push({ id, type, title, message, timeout });
    
    // 自动移除通知
    setTimeout(() => {
      removeNotification(id);
    }, timeout);
  }
  
  function removeNotification(id: string) {
    const index = notifications.value.findIndex(n => n.id === id);
    if (index !== -1) {
      notifications.value.splice(index, 1);
    }
  }
  
  function deleteTask(taskId: string) {
    const taskIndex = tasks.value.findIndex(task => task.task_id === taskId);
    if (taskIndex !== -1) {
      tasks.value.splice(taskIndex, 1);
      
      // 如果删除的是当前选中的任务，清除选中状态
      if (selectedTaskId.value === taskId) {
        selectedTaskId.value = null;
      }
    }
  }
  
  // 在return语句中添加新的方法和状态
  return { 
    tasks,
    selectedTaskId, 
    clientId,
    connectionId,
    notifications,
    currentTaskType, // 添加当前任务类型
    sortedTasks,
    addTask, 
    updateTaskStatus,
    updateMetadataStatus,
    clearAllTasks,
    deleteTask,
    addNotification,
    removeNotification,
    setSelectedTaskId: (id: string | null) => selectedTaskId.value = id,
    setConnectionId: (id: string) => connectionId.value = id,
    setCurrentTaskType: (type: 'DOI' | 'JiangSu') => currentTaskType.value = type // 添加设置当前任务类型的方法
  };
});